package com.well.register.eventAndlistener;

import com.well.register.console.domain.Job;
import com.well.register.console.service.JobService;
import com.well.register.console.service.ServerService;
import com.well.register.event.ServerHandler;
import com.well.rpc.model.RegisterModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * server down lister
 *  用来监听服务down事件，并进行残余工作处理
 * </p>
 *
 * @author weedo
 * @since 2022/8/18
 */
@Slf4j
@Component
public class ServerDownLister implements ApplicationListener<ServerDownEvent> {

    @Resource
    private JobService jobService;
    @Resource
    private ServerService serverService;

    @Override
    public void onApplicationEvent(ServerDownEvent serverDownEvent) {
        RegisterModel registerModel = serverDownEvent.getRegisterModel();
        cancelJobs(registerModel);
    }

    /**
     * 取消定制任务
     *
     * @param registerModel
     */
    private void cancelJobs(RegisterModel registerModel) {
        int count = serverService.countActivityServer(registerModel);
        if (count > 0) {
            return;
        }
        List<Job> lists = jobService.getJobs(registerModel);
        lists.forEach((job) -> {
            ServerHandler.cancelScheduledFuture(registerModel, job.getJobName());
        });
    }
}
